package top.toptimus.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * 阿里云数据源配置
 */
@Configuration
@EnableJpaRepositories(basePackages = "top.toptimus.publicCloudService.jpa",
        entityManagerFactoryRef = "localContainerEntityManagerFactoryBeanAliyun",
        transactionManagerRef = "platformTransactionManagerAliyun")
public class JpaConfigAliyun {
    @Autowired
    @Qualifier("primaryDataSource")
    private DataSource primaryDataSource;


    @Autowired
    private JpaProperties jpaProperties;

    @Primary
    @Bean(name = "localContainerEntityManagerFactoryBeanAliyun")
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBeanAliyun(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(primaryDataSource)
                .properties(jpaProperties.getProperties())
                .packages("top.toptimus.publicCloudService.jpa.dao.aliyun")
                .persistenceUnit("persistenceUnitAliyun")
                .build();

    }

    @Primary
    @Bean(name = "platformTransactionManagerAliyun")
    PlatformTransactionManager platformTransactionManagerAliyun(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = localContainerEntityManagerFactoryBeanAliyun(builder);
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean.getObject());
    }

}
